package com.zld.smarket.controller;

import com.zld.smarket.pojo.Stock;
import com.zld.smarket.pojo.Stockin;
import com.zld.smarket.pojo.Stockout;
import com.zld.smarket.result.ExceptionMsg;
import com.zld.smarket.result.ResponseData;
import com.zld.smarket.service.StockService;
import com.zld.smarket.service.StockoutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/stockout")
public class StockoutController {

    @Autowired
    private StockoutService stockoutService;

    @Autowired
    private StockService stockSerinvice;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ResponseData findList(Integer page, Integer limit){
        return  stockoutService.findList(page,limit);
    }

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public ResponseData search(String s,Integer page, Integer limit){
        return  stockoutService.search(s,page,limit);
    }


    @RequestMapping(value = "/add")
    public ResponseData add(Stockout stockout){

        Long i=stockout.getStockoutNo();
        if(stockoutService.selectbyno(i)>0){
            return new ResponseData(ExceptionMsg.ADDERROR);
        }else {
            stockout.setStockoutDate(new Date());
            stockout.setSurplus(stockout.getStockoutNum());
            List<Stock> stocks =stockSerinvice.selectbyGoodsno(stockout.getGoodsNo(),stockout.getSupplierId(),stockout.getStorehouseNo());
            if(stocks.size()==1){
                    if(stocks.get(0).getStockNum()<stockout.getStockoutNum()){
                        return new ResponseData(ExceptionMsg.OUTOFNUM);
                    }else {
                        Integer integer1 =stockSerinvice.reduceStockNum(stockout.getGoodsNo(),stockout.getSupplierId(),stockout.getStorehouseNo(),stockout.getStockoutNum());
                        Integer integer = stockoutService.addStockout(stockout);
                        return new ResponseData(ExceptionMsg.SUCCESS);

                    }
            }else {
                return new ResponseData(ExceptionMsg.EMPTY);
            }

        }
    }
}
